<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card shadow="hover">
      <el-row :gutter="20">
        <el-col :span="8">
          <div class="grid-content bg-purple">
            <el-input
              placeholder="请输入内容"
              clearable
              @clear="getUserList"
              v-model="queryInfo.query">
              <el-button type="primary" slot="append" icon="el-icon-search" @click="getUserList"></el-button>
            </el-input>
          </div>
        </el-col>
        <el-col :span="4" :offset="12">
          <div class="grid-content bg-purple">
            <el-button type="success" @click="addUserDialog" round>添加用户</el-button>
          </div>
        </el-col>
      </el-row>
      <el-table :data="userList" stripe>
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.state" @change="userStateChanged(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button circle size="mini" type="primary" icon="el-icon-edit" @click="showEditDialog(scope.row)" ></el-button>
            <el-button circle size="mini" type="danger" icon="el-icon-delete" @click="removeUserById(scope.row.id)"></el-button>
            <el-tooltip effect="dark" content="修改角色" placement="top-start" :enterable="false">
              <el-button circle size="mini" type="warning" icon="el-icon-setting"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pageNum"
        :page-sizes="[1, 2, 5, 8]"
        :page-size="queryInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>

    <el-dialog
      title="添加用户"
      :visible.sync="addDialogVisible"
      width="50%"
      center
      @close="dialogClosed">
      <el-form status-icon :model="addUserForm" :rules="addUserFormRoles" ref="addUserFormRefs" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addUserForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addUserForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addUserForm.email"></el-input>
        </el-form-item>
        <el-form-item label="联系方式" prop="mobile">
          <el-input v-model="addUserForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="addDialogVisible = false" round>取 消</el-button>
    <el-button type="primary" @click="addUser" round>确 定</el-button>
  </span>
    </el-dialog>
<!--修改用户信息的对话框-->
    <el-dialog
    title="修改用户信息"
    :visible.sync="editDialogVisible"
    width="50%"
    center
    @close="editDialogClosed">
      <el-form status-icon :model="editUserForm" :rules="editUserFormRoles" ref="editUserFormRefs" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editUserForm.username" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editUserForm.email"></el-input>
        </el-form-item>
        <el-form-item label="联系方式" prop="mobile">
          <el-input v-model="editUserForm.mobile"></el-input>
        </el-form-item>
      </el-form>
    <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false" round>取 消</el-button>
        <el-button type="primary" @click="editUser" round>确 定</el-button>
  </span>
    </el-dialog>
    <el-card>
      <el-carousel :interval="3000" type="card" height="400px" indicator-position="outside">
        <el-carousel-item v-for="item in 6" :key="item">
          <el-image fit="contain" src="https://cube.elemecdn.com/6/94/4d3ea53c084bad6931a56d5158a48jpeg.jpeg">
            <div slot="placeholder" class="image-slot">
              加载中<span class="dot">...</span>
            </div>
          </el-image>
        </el-carousel-item>
      </el-carousel>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'Users',
  data () {
    const checkEmail = (rule, value, callback) => {
      if (!value) {
        callback()
      } else {
        const reg = /^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$/
        const email = reg.test(value)
        if (!email) {
          callback(new Error('邮箱格式如:admin@163.com'))
        } else {
          callback()
        }
      }
    }
    const checkMobile = (rule, value, callback) => {
      if (!value) {
        return new Error('请输入电话号码')
      } else {
        const reg = /^1[3|4|5|7|8][0-9]\d{8}$/
        const isPhone = reg.test(value)
        value = Number(value) // 转换为数字
        if (typeof value === 'number' && !isNaN(value)) { // 判断是否为数字
          value = value.toString() // 转换成字符串
          if (value.length < 0 || value.length > 12 || !isPhone) { // 判断是否为11位手机号
            callback(new Error('手机号码格式如:138xxxx8754'))
          } else {
            callback()
          }
        } else {
          callback(new Error('请输入电话号码'))
        }
      }
    }
    return {
      queryInfo: {
        query: '',
        pageNum: 1,
        pageSize: 2
      },
      userList: [],
      total: 0,
      addDialogVisible: false,
      editDialogVisible: false,
      addUserForm: {
        id: 0,
        username: '',
        password: '',
        mobile: '',
        email: ''
      },
      editUserForm: {
        id: 0,
        username: '',
        mobile: '',
        email: ''
      },
      addUserFormRoles: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 1, max: 5, message: '长度在 1 到 5 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      editUserFormRoles: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 1, max: 5, message: '长度在 1 到 5 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.getUserList()
  },
  methods: {
    async getUserList () {
      const { data: res } = await this.$http.get('/userInfo/getUsersInfo', {
        params: this.queryInfo
      })
      if (res.status !== 200) return this.$message.error('获取用户列表失败！')
      this.userList = res.data.userVO
      this.total = res.data.total
    },
    handleSizeChange (newSize) {
      this.queryInfo.pageSize = newSize
      this.getUserList()
    },
    handleCurrentChange (newPage) {
      this.queryInfo.pageNum = newPage
      this.getUserList()
    },
    async userStateChanged (userInfo) {
      const { data: res } = await this.$http.get('/userEdit/editUserState', { params: { state: userInfo.state, id: userInfo.id } })
      if (res.status !== 200) {
        userInfo.state = !userInfo.state
        return this.$message.error('更新用户状态失败！')
      }
      this.$message.success('更新用户状态成功！')
    },
    addUserDialog () {
      this.addDialogVisible = true
    },
    showEditDialog (userInfo) {
      this.editDialogVisible = true
      this.editUserForm.id = userInfo.id
      this.editUserForm.username = userInfo.username
      this.editUserForm.email = userInfo.email
      this.editUserForm.mobile = userInfo.mobile
    },
    dialogClosed () {
      this.$refs.addUserFormRefs.resetFields()
    },
    editDialogClosed () {
      // this.$refs.editUserFormRefs.resetFields()
    },
    addUser () {
      this.$refs.addUserFormRefs.validate(async valid => {
        // eslint-disable-next-line no-useless-return
        if (!valid) return
        const { data: res } = await this.$http.post('/userEdit/addUser', this.addUserForm)
        if (res.status !== 201) return this.$message.error('添加用户失败')
        this.$message.success('添加用户成功')
        // 关闭对话框
        this.addDialogVisible = false
        await this.getUserList()
      })
    },
    editUser () {
      this.$refs.editUserFormRefs.validate(async valid => {
        // eslint-disable-next-line no-useless-return
        if (!valid) return
        const { data: res } = await this.$http.post('/userEdit/editUser', this.editUserForm)
        if (res.status !== 201) return this.$message.error('修改用户信息失败')
        this.$message.success('修改用户信息成功')
        // 关闭对话框
        this.editDialogVisible = false
        await this.getUserList()
      })
    },
    async removeUserById (userId) {
      // 点击确定后，返回值是confirm 字符串，取消后，内部抛出异常，捕获异常并返回cancel字符串
      const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(error => error)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已经取消删除！')
      }
      const { data: result } = await this.$http.delete('/userEdit/deleteUser', { params: { id: userId } })
      if (result.status !== 200) {
        return this.$message.error('删除失败！')
      }
      this.$message.success('删除成功！')
    }
  }
}
</script>

<style scoped>
.el-breadcrumb {
  margin-bottom: 10px;
}

.el-card {
  box-shadow: 0 1px 1px rgba(0, 0, 0, .15) !important;
}

.el-table {
  margin-top: 20px;
  font-size: 12px;
  text-align: center;
}

.el-pagination {
  margin-top: 20px;
}

</style>
